﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace AMing.Core.Http
{
    public class DownloadHelper
    {
        /// <summary>
        /// HttpGet(异步)
        /// </summary>
        public void Download_Async(string url, string savePath,
            Action<int> downloadProgressPercentage,
            Action<long, long> downloadProgress,
            Action<bool> downloadCompleted)
        {
            try
            {
                savePath = IO.Path.GetApplicationPath(savePath);
                string folder = System.IO.Path.GetDirectoryName(savePath);
                string tempFolder = string.Format("{0}\\download_temp", folder);
                string filename = System.IO.Path.GetFileName(savePath);
                string tempfile = System.IO.Path.Combine(tempFolder, filename);

                if (!System.IO.Directory.Exists(folder))
                {
                    System.IO.Directory.CreateDirectory(folder);
                }
                if (!System.IO.Directory.Exists(tempFolder))
                {
                    System.IO.Directory.CreateDirectory(tempFolder);
                }

                WebClient webClient = new WebClient();
                webClient.DownloadProgressChanged += (dpc_sender, dpc_e) =>
                {
                    downloadProgressPercentage(dpc_e.ProgressPercentage);
                    downloadProgress(dpc_e.BytesReceived, dpc_e.TotalBytesToReceive);
                };
                webClient.DownloadFileCompleted += (dfc_sender, dfc_e) =>
                {
                    MoveTempFile(tempfile, savePath);
                    downloadCompleted(!dfc_e.Cancelled);
                };
                downloadProgressPercentage(0);

                webClient.DownloadFileAsync(new Uri(url), tempfile);

            }
            catch (Exception ex)
            {
                downloadCompleted(false);
            }
        }
        /// <summary>
        /// 移动临时文件
        /// </summary>
        /// <param name="tempPath"></param>
        /// <param name="savePath"></param>
        private void MoveTempFile(string tempPath, string savePath)
        {
            try
            {
                System.IO.FileInfo tempFile = new System.IO.FileInfo(tempPath);
                System.IO.FileInfo saveFile = new System.IO.FileInfo(savePath);
                if (!tempFile.Exists)
                {
                    return;
                }
                if (saveFile.Exists)
                {
                    saveFile.Delete();
                }
                tempFile.MoveTo(savePath);
            }
            catch (Exception)
            {
            }
        }
    }
}
